<template>
	<div class="timeline-chart-wrapper">
		<!-- 图表容器 -->
		<div ref="chartRef" class="timeline-chart-container">
			<!-- 图表说明 -->
			<div class="chart-explanation">
				<div class="explanation-item">
					<span class="legend-dot time-progress"></span>
					<span class="legend-text">时间进度线：时间推移基准线（从0线性递增到计划总量）</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

interface Props {
	chartData: any[];
	areaName: string;
	showTimeProgress?: boolean; // 是否显示时间进度线
}

const props = withDefaults(defineProps<Props>(), {
	showTimeProgress: true
});

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

// 计算时间进度数据
const calculateTimelineData = () => {
	if (!props.chartData || props.chartData.length === 0) return null;

	// 获取今天的日期
	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	const totalDays = props.chartData.length;
	
	// 获取最后一天的计划完工数作为时间进度线的终点
	const finalPlanEnd = props.chartData[props.chartData.length - 1]?.planEnd || 0;
	
	// 处理数据，计算时间进度率和完工进度
	const timelineData = props.chartData.map((item, index) => {
		const dateStr = item.date;
		const isTodayOrBefore = dateStr <= todayStr;
		const currentDay = index + 1;
		
		// 获取完工数据
		const planEndTotal = item.planEnd || 0;
		const actualEndTotal = isTodayOrBefore ? (item.actualEnd || 0) : null;
		
		// 计算时间进度：从0线性递增到最终计划完工数
		// 确保最后一天完全重合
		const timeProgressValue = index === totalDays - 1 
			? finalPlanEnd 
			: (currentDay / totalDays) * finalPlanEnd;
		

		return {
			date: dateStr,
			dayNumber: currentDay,
			totalDays: totalDays,
			timeProgressValue: timeProgressValue,
			planEnd: planEndTotal,
			actualEnd: actualEndTotal,
			isTodayOrBefore: isTodayOrBefore
		};
	});

	return timelineData;
};

const renderChart = () => {
	if (!chartRef.value || !props.chartData || props.chartData.length === 0) return;

	const timelineData = calculateTimelineData();
	if (!timelineData) return;

	// 获取最后一天的计划完工数作为时间进度线的终点
	const finalPlanEnd = props.chartData[props.chartData.length - 1]?.planEnd || 0;

	// 格式化日期为 MM-DD
	const days = timelineData.map((d: any) => {
		const date = new Date(d.date);
		const mm = String(date.getMonth() + 1).padStart(2, '0');
		const dd = String(date.getDate()).padStart(2, '0');
		return `${mm}-${dd}`;
	});

	// 准备数据
	const planEndData = timelineData.map(d => d.planEnd);
	const actualEndData = timelineData.map(d => d.actualEnd);
	const timeProgressData = timelineData.map(d => d.timeProgressValue); // 时间进度线使用线性计算值
	
	// 计算计划完工数的最大值，用于设置右侧Y轴的刻度范围
	const maxPlanEnd = Math.max(...planEndData.filter(val => val !== null && val !== undefined));
	const rightYAxisMax = Math.ceil(maxPlanEnd * 1.1); // 稍微放大一点给时间进度线留出空间

	if (chart) chart.dispose();

	chart = echarts.init(chartRef.value);
	chart.setOption({
		title: {
			text: `${props.areaName} - 时间轴完工情况与时间进度`,
			left: 'center',
			textStyle: {
				fontSize: 14,
				fontWeight: 'bold',
				color: '#333'
			}
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
				label: {
					backgroundColor: '#6a7985'
				}
			},
			formatter: function(params: any) {
				const dataIndex = params[0].dataIndex;
				const data = timelineData[dataIndex];
				let result = `${params[0].axisValue} (第${data.dayNumber}天/${data.totalDays}天)<br/>`;
				
				result += `时间进度线: ${Math.round(data.timeProgressValue)}<br/>`;
				result += `计划完工: ${data.planEnd}<br/>`;
				
				if (data.actualEnd !== null) {
					result += `实际完工: ${data.actualEnd}<br/>`;
				}
				
				return result;
			}
		},
		legend: {
			data: props.showTimeProgress 
				? ['时间进度线', '计划完工', '实际完工']
				: ['计划完工', '实际完工'],
			top: 35,
			textStyle: { fontSize: 11 }
		},
		grid: {
			left: '5%',
			right: '5%',
			bottom: '15%',
			top: '20%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: days,
			axisLabel: {
				rotate: 45,
				interval: 0,
				fontSize: 10,
				color: '#666'
			},
			axisLine: {
				lineStyle: { color: '#ddd' }
			},
			axisTick: { show: false }
		},
		yAxis: [
			{
				type: 'value',
				name: '完工数',
				position: 'left',
				axisLabel: {
					fontSize: 10,
					color: '#666'
				},
				axisLine: { show: false },
				axisTick: { show: false },
				splitLine: {
					lineStyle: {
						color: '#f0f0f0',
						type: 'dashed'
					}
				}
			},
		],
		series: [
			{
				name: '计划完工',
				type: 'line',
				data: planEndData,
				smooth: true,
				symbol: 'circle',
				symbolSize: 4,
				lineStyle: {
					width: 2,
					color: '#5470c6'
				},
				itemStyle: {
					color: '#5470c6'
				},
				areaStyle: {
					color: {
						type: 'linear',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [{
							offset: 0, color: 'rgba(84, 112, 198, 0.3)'
						}, {
							offset: 1, color: 'rgba(84, 112, 198, 0.1)'
						}]
					}
				}
			},
			{
				name: '实际完工',
				type: 'line',
				data: actualEndData,
				smooth: true,
				symbol: 'circle',
				symbolSize: 4,
				lineStyle: {
					width: 2,
					color: '#91cc75'
				},
				itemStyle: {
					color: '#91cc75'
				},
				areaStyle: {
					color: {
						type: 'linear',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [{
							offset: 0, color: 'rgba(145, 204, 117, 0.3)'
						}, {
							offset: 1, color: 'rgba(145, 204, 117, 0.1)'
						}]
					}
				},
				connectNulls: false
			},
			...(props.showTimeProgress ? [
				{
					name: '时间进度线',
					type: 'line',
					yAxisIndex: 0,
					data: timeProgressData,
					smooth: false,
					symbol: 'none',
					lineStyle: {
						width: 2,
						color: '#ee6666',
						type: 'solid'
					},
					itemStyle: {
						color: '#ee6666'
					}
				}
			] : [])
		]
	});

	chart.resize();
};

const handleResize = () => {
	if (chart) {
		chart.resize();
	}
};

// 暴露resize方法给父组件
const resize = () => {
	handleResize();
};

onMounted(() => {
	nextTick(() => {
		renderChart();
		window.addEventListener('resize', handleResize);
	});
});

onBeforeUnmount(() => {
	if (chart) {
		chart.dispose();
		chart = null;
	}
	window.removeEventListener('resize', handleResize);
});

watch(() => props.chartData, () => {
	nextTick(() => {
		renderChart();
	});
}, { deep: true });

watch(() => props.areaName, () => {
	nextTick(() => {
		renderChart();
	});
});

watch(() => props.showTimeProgress, () => {
	nextTick(() => {
		renderChart();
	});
});

// 暴露方法给父组件
defineExpose({
	resize
});
</script>

<style scoped>
.timeline-chart-wrapper {
	width: 100%;
	height: 100%;
	min-height: 300px;
}

.timeline-chart-container {
	width: 100%;
	height: 100%;
	min-height: 300px;
	position: relative;
}

.chart-explanation {
	position: absolute;
	bottom: 10px;
	left: 10px;
	right: 10px;
	background: rgba(255, 255, 255, 0.95);
	padding: 8px 12px;
	border-radius: 4px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	border: 1px solid var(--el-border-color-lighter);
	z-index: 10;
	font-size: 12px;
	color: var(--el-text-color-secondary);
}

.explanation-item {
	display: flex;
	align-items: center;
	margin-bottom: 4px;
}

.explanation-item:last-child {
	margin-bottom: 0;
}

.legend-dot {
	width: 8px;
	height: 8px;
	border-radius: 50%;
	margin-right: 6px;
	flex-shrink: 0;
}

.legend-dot.time-progress {
	background-color: #ee6666;
}


.legend-text {
	color: #666;
	font-size: 11px;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.chart-explanation {
		font-size: 10px;
		padding: 6px 8px;
	}
	
	.legend-text {
		font-size: 9px;
	}
	
	.legend-dot {
		width: 6px;
		height: 6px;
	}
}
</style>